import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.locks.InterProcessMutex;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class CuratorByLockDemo {
    public static void main(String[] args) {
        CuratorFramework zkClient = getZkClient();
        String lockPath = "/lock";
        //创建一个可重入排他锁
        InterProcessMutex lock = new InterProcessMutex(zkClient, lockPath);
        //模拟50个线程抢锁
        for (int i = 0; i < 50; i++) {
            new Thread(new TestThread(i, lock)).start();
        }
    }

        private static CuratorFramework getZkClient() {
            String zkServerAddress = "192.168.49.57:2181";
            ExponentialBackoffRetry retryPolicy =
                    new ExponentialBackoffRetry(1000, 3, 5000);
            CuratorFramework zkClient = CuratorFrameworkFactory.builder()
                     //连接地址
                    .connectString(zkServerAddress)
                    //session会话超时时间
                    .sessionTimeoutMs(5000)
                    .connectionTimeoutMs(5000)
                    //策略： 重试策略
                    .retryPolicy(retryPolicy)
                    //构建出来
                    .build();
            zkClient.start();
            return zkClient;
        }

    static class TestThread implements Runnable {
        private Integer threadFlag;
        private InterProcessMutex lock;

        public TestThread(Integer threadFlag, InterProcessMutex lock) {
            this.threadFlag = threadFlag;
            this.lock = lock;
        }

        @Override
        public void run() {
            try {
                lock.acquire();
                System.out.println("第"+threadFlag+"线程获取到了锁");
                //等到1秒后释放锁
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                try {
                    lock.release();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
